// JavaScript Document
//variables de alcance GLOBAL

var misVehiculosHash = new Hashtable();

//var vehiculosSeleccionadosIds = CUENTA_SELECCIONADA;

var misVehiculosMarkersHash = new Hashtable(); //hash con los Iconos de los vehiculos (se van creando a medida que se van seleccionando)
var misVehiculosSentidoHash = new Hashtable(); //hash con los iconos de sentido de los vehiculos (se van creando a medida que se van seleccionando)
var misVehiculosSeguiMarker = null;
var misVehiculosSelecMarker = null;

var vehiculosLayer = new OpenLayers.Layer.Markers( "Vehiculos" ); //capa del mapa en donde se imprimen los iconos pertenecientes a los vehiculos.

var reqHandlerMisVehiculos = null;

var reqHandler = null;

var orderTypeMisVehiculos = "A";

/**************************FUNCIONES PARA PANTALLA PRINCIPAL****************************/
	
	function vaciarSelector(select, fields) {
		for (i = 0; i <= fields.length; i++) {
			select.options[1] = null;
		}
	}
	
	function getTextoFromCheckBox(check) {
		var texto = check.parentNode.parentNode.innerHTML;
		pos = texto.indexOf('inputLBL">');
		if (pos == -1) {
			pos = texto.indexOf('inputLBL>');
		}
		texto = texto.substring(pos + 1);
		texto = texto.substring(texto.indexOf('>') + 1, texto.indexOf('<'));
		return texto;	
	}
	
	function verificarChecks()
	{
		fields = document.getElementsByName('box[]');
		for (i = 0; i < fields.length; i++) {
			if (fields[i].checked) return true;
		}
		return false;
	}
	
	function checkAll()
	{
		var fields = document.getElementsByName('box[]');
		var select = document.getElementById("selectSeguimiento");
		var cuenta = cuentaSelectSegui;
		vaciarSelector(select, fields);
		reqParams = "cuentas=";
		for (i = 0; i < fields.length; i++) {
	    	if (!fields[i].checked) {
				fields[i].checked = true;
	    	}
	    	texto = getTextoFromCheckBox(fields[i]);
			variable = new Option(texto, fields[i].value);
			select.options[select.options.length] = variable;
			if (cuenta == fields[i].value) {
				select.options[i + 1].selected = true;				
			}
			reqParams = reqParams + fields[i].value + ",";
		}
		reqParams = reqParams.substring(0,reqParams.length -1);
		RefreshForm();
	}

	function uncheckAll() {
		fields = document.getElementsByName('box[]');
		for (i = 0; i < fields.length; i++) {  
			fields[i].checked = false ;
			if (misVehiculosMarkersHash.containsKey(fields[i].value.toString())){
				vehiculosLayer.removeMarker(misVehiculosMarkersHash.get(fields[i].value.toString()));
				vehiculosLayer.removeMarker(misVehiculosSentidoHash.get(fields[i].value.toString()));
				misVehiculosMarkersHash.remove(fields[i].value.toString());
				misVehiculosSentidoHash.remove(fields[i].value.toString());
				if (misVehiculosSeguiMarker!=null){
					vehiculosLayer.removeMarker(misVehiculosSeguiMarker);
					misVehiculosSeguiMarker=null;
				}
				if (misVehiculosSelecMarker!=null){
					vehiculosLayer.removeMarker(misVehiculosSelecMarker);
					misVehiculosSelecMarker=null;
				}
			}
		}
		select = document.getElementById("selectSeguimiento");
		for (i = 0; i <= fields.length; i++) {
			select.options[1] = null;
		}
		cuentaSelectSegui = '-1';
		cuentaSelectSelection = '-1';
		
		reqParams = "cuentas=";
		RefreshForm();
	}
	
	function addParameter(valor) {
		if (reqParams == "cuentas=") {
			 reqParams += valor;
			 return;
		}
		reqParams = reqParams +  "," + valor;
	}
	
	function removeParameter(valor) {
		if (valor == cuentaSelectSegui) {
			cuentaSelectSegui = '-1';
		}
		refreshParameters();
	}
	
	function refreshParameters() {
		fields = document.getElementsByName('box[]');
		var nuevoReqParams = "cuentas=";
		for (i = 0; i < fields.length; i++) {
			if (fields[i].checked) { 
				nuevoReqParams += fields[i].value + ",";
			}
		}
		if (nuevoReqParams != "cuentas=") {
			nuevoReqParams = nuevoReqParams.substring(0, nuevoReqParams.length -1);
		}
		reqParams = nuevoReqParams;
		
	}
	
	function clickCheckBox(check)
	{
		check = check.parentNode.getElementsByTagName('input')[0];
		var cuenta = cuentaSelectSegui;
		var select = document.getElementById("selectSeguimiento");
		var indiceActual = select.selectedIndex; 
		var fields = document.getElementsByName('box[]');		
		if (check.checked) // tengo que agregarlo al select
		{
			vaciarSelector(select, fields);
			for (i = 0; i < fields.length; i++) {
				if (fields[i].checked) { 
					texto = getTextoFromCheckBox(fields[i]);
					variable = new Option(texto, fields[i].value);
					select.options[select.options.length] = variable;
				}
			}
			for (i = 1; i < select.options.length; i++) {
				if (select.options[i].value == cuentaSelectSegui) {
					select.options[i].selected = true;
				}
			}
			addParameter(check.value);
		}
		else { // lo tengo que borrar del select
			var indiceSelect = 0;
			for (i = 0; i < select.options.length ; i++) {	
				var selectActual = select.options[i];
				if (check.value == selectActual.value) {
					indiceSelect = i ;
					break;
				}
			}
			select.options[indiceSelect] = null;
			
			if (indiceActual == indiceSelect) {
				if (select.options.length >= 1) {
					select.options[0].selected = true;
					if (misVehiculosSeguiMarker!=null){
						vehiculosLayer.removeMarker(misVehiculosSeguiMarker);
						misVehiculosSeguiMarker=null;
					}
					cuentaSelectSegui = '-1';
				} 
			}
			
			//si 
			if (cuentaSelectSelection.toString() == check.value.toString()){
				if (misVehiculosSelecMarker!=null){
					vehiculosLayer.removeMarker(misVehiculosSelecMarker);
					misVehiculosSelecMarker=null;
				}
				cuentaSelectSelection = '-1';
			}
						
			if (misVehiculosMarkersHash.containsKey(check.value.toString())){
				vehiculosLayer.removeMarker(misVehiculosMarkersHash.get(check.value.toString()));
				vehiculosLayer.removeMarker(misVehiculosSentidoHash.get(check.value.toString()));
				misVehiculosMarkersHash.remove(check.value.toString());
				misVehiculosSentidoHash.remove(check.value.toString());
			}
			removeParameter(check.value);
		}
		RefreshForm();
	}
	
	function ordenarMisVehiculos(){
		if (orderTypeMisVehiculos=="A"){
			orderTypeMisVehiculos="D";
			printTableMisVehiculos();
			document.getElementById('orderBTNmisVehiculos').style.backgroundImage='url(images/minimenu/BTNorderAZ.gif)';
		}
		else{
			orderTypeMisVehiculos="A";
			printTableMisVehiculos();
			document.getElementById('orderBTNmisVehiculos').style.backgroundImage='url(images/minimenu/BTNorderZA.gif)';
		}
	}
	
	function printTableMisVehiculos(){		
		tabla = '<table width="260">';
		misVehiculosList = misVehiculosHash.values();
		var sortArray = new SortArray(misVehiculosList,"QUICKSORT");
		sortArray.ordenar(orderTypeMisVehiculos,'label');
		for (var i=0; i<misVehiculosList.length; i++){
			checked = '';
			var cuentasSelectedString = reqParams.replace('cuentas=', '');
			var cuentasSelectedArray = new Array();
			if (trim(cuentasSelectedString)!='')
				cuentasSelectedArray = cuentasSelectedString.split(',');			
			if ((misVehiculosList[i].id == cuentaSelectSegui)||(indexOfArray(cuentasSelectedArray,misVehiculosList[i].id.toString())!=-1)){
				checked = 'checked';
			}
			tabla += '<tr>';
			tabla += '<td width="19">';		
			tabla += '<input type="checkbox" name="box[]" value="'+misVehiculosList[i].id+'" '+checked+' onClick="clickCheckBox(this);" >';
			tabla += '</td>';
			tabla += '<td><span class="inputLBL">'+misVehiculosList[i].label+'</span></td>';
			tabla += '</tr>';
		}
		tabla += '</table>';
		document.getElementById('divListaVehiculos').innerHTML = tabla;
	}

	

/****************************CARGA DE MOVILES********************************/

	function OnReadyStateChangeMisVehiculos(){
		ready = reqHandlerMisVehiculos.readyState;
		if (ready == READY_STATE_COMPLETE) {
			misVehiculosJSON = reqHandlerMisVehiculos.responseText.parseJSON();
			if (misVehiculosJSON.length != 'undefined') {				
				for (i=0; i<misVehiculosJSON.length; i++){
					misVehiculosHash.put(misVehiculosJSON[i].id,misVehiculosJSON[i]);
				}
			vehiculosCargadosFlag = true;
			printTableMisVehiculos();
			CargarSeguimiento();
			CargarHistorico();
			CargarMisGrupos();//carga los grupos de "MisPuntos"
			CargarMisZonas();
			}
		$j("#iconoMapa").removeClass().addClass("icono_mapa");
		autoRefreshFlag = 0;
		}
	}
	
	function CargarMisVehiculos() {
		map.addLayer(vehiculosLayer);
    	reqParamMisVehiculos = "COMMAND=MOVILES";
    	reqParamMisVehiculos += "&CUENTA=" + MOVIL_ID;
		reqParamMisVehiculos += "&OBJETIVO=" + OBJETIVO;
    	document.getElementById("busyImg").style.visibility = "visible";
		autoRefreshFlag = 1;
    	if (msie) 
            reqHandlerMisVehiculos = new ActiveXObject("Microsoft.XMLHTTP");
        else
            reqHandlerMisVehiculos = new XMLHttpRequest();
        reqHandlerMisVehiculos.onreadystatechange = OnReadyStateChangeMisVehiculos;    
        reqHandlerMisVehiculos.open("POST", "querycontroller.php", true);
        reqHandlerMisVehiculos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		reqHandlerMisVehiculos.send(reqParamMisVehiculos);
    }
	
//**************************FUNCIONES PARA MANIPULAR VEHICULOS(GMAPICONS) EN EL MAPA************************//

	function clearIconCars(){
		vehiculosMarkersArray = misVehiculosMarkersHash.values();
		vehiculosMarkersSentido = misVehiculosSentidoHash.values();
		for (i=0; i<vehiculosMarkersArray.length; i++){
			map.removeOverlay(vehiculosMarkersArray[i]);
			map.removeOverlay(vehiculosMarkersSentido[i]);
		}
		misVehiculosMarkersHash.clear();
		misVehiculosSentidoHash.clear();
	}
	
	function createMarker(point, icon, id) {
		marker = new OpenLayers.Marker(point, icon);
                marker.events.register('click', marker, function(evt) { 
                	//marker.openInfoWindowHtml(message);
    			cuentaSelectSelection = id;
				if (misVehiculosSelecMarker!=null){
					vehiculosLayer.removeMarker(misVehiculosSelecMarker);
					misVehiculosSelecMarker=null;
				}
				
				cleanAllStates();
    			AccordionMenu.openPanelNumber(2);
    			RefreshForm();	
                	OpenLayers.Event.stop(evt); 
                	});
  		return marker;
	}
	
	function createMarkerSentido(point, icon) {
		marker = new OpenLayers.Marker(point, icon);
  		return marker;
	}
	
	function obtenerLabelSentido(sentido) {
		if (sentido >= 22 && sentido <= 67)   return "ne";
        if (sentido >= 68 && sentido <= 112)  return "e";
    	if (sentido >= 113 && sentido <= 157) return "se";
    	if (sentido >= 158 && sentido <= 202) return "s";
    	if (sentido >=203  && sentido <= 247) return "so";
    	if (sentido >= 248 && sentido <= 292) return "o";
    	if (sentido >= 293 && sentido <= 337) return "no";
    	if ((sentido >= 338 && sentido <= 360) || ((sentido >= 0 && sentido <= 21))) return "n";
    	return "";
	}
	
	function obtenerPalabraSentido(sentido) {
    	if (sentido >= 22 && sentido <= 67)   return "NORESTE";
        if (sentido >= 68 && sentido <= 112)  return "ESTE";
    	if (sentido >= 113 && sentido <= 157) return "SURESTE";
    	if (sentido >= 157 && sentido <= 202) return "SUR";
    	if (sentido >=203  && sentido <= 247) return "SUROESTE";
    	if (sentido >= 248 && sentido <= 292) return "OESTE";
    	if (sentido >= 293 && sentido <= 337) return "NOROESTE";
    	if ((sentido >= 338 && sentido <= 360) || ((sentido >= 0 && sentido <= 21))) return "NORTE";
		return "";
    }
	
	function putIconCar(carId)
	{	
		
		car = misVehiculosHash.get(carId);
		
		if (car.POSIMOVIL==null){
			alert('Imposible visualizar este movil. Se desconocen reportes de su posicionamiento actual e historico.');
			return;
		}
		
       	point = new OpenLayers.LonLat(parseFloat(car.POSIMOVIL.longitud),  parseFloat(car.POSIMOVIL.latitud)).transform(displayProjection, projection);
		
		if ((cuentaSelectSegui.toString()=='-1')&&(misVehiculosSeguiMarker!=null)){
			vehiculosLayer.removeMarker(misVehiculosSeguiMarker);
			misVehiculosSeguiMarker=null;
		}
		
		if ((cuentaSelectSelection.toString()=='-1')&&(misVehiculosSelecMarker!=null)){
			vehiculosLayer.removeMarker(misVehiculosSelecMarker);
			misVehiculosSelecMarker=null;
		}
	
		if (car.id == cuentaSelectSegui){//en seguimiento?
			if (misVehiculosSeguiMarker!=null)
				vehiculosLayer.removeMarker(misVehiculosSeguiMarker);
			misVehiculosSeguiMarker =  createMarkerSentido(point, seguimientoIcon);
			vehiculosLayer.addMarker(misVehiculosSeguiMarker);			
		}
		else if (car.id == cuentaSelectSelection){ //en seleccion?
			if (misVehiculosSelecMarker!=null)
				vehiculosLayer.removeMarker(misVehiculosSelecMarker);
			misVehiculosSelecMarker = createMarkerSentido(point, seleccionadoIcon);
			vehiculosLayer.addMarker(misVehiculosSelecMarker);
		}		
				
		var keySentido = obtenerLabelSentido(car.POSIMOVIL.sentido);
		keySentido = (eval(car.POSIMOVIL.velocidad) == 0) ? keySentido+"Inactive" : keySentido+"Active";
		var iconSentido = sentidoIcons.get(keySentido);		
		
		if (!(misVehiculosMarkersHash.containsKey(carId))){
			var keyMovil = car.tipoAvl.toString();
			var iconMovil = movilIcons.get(keyMovil);
			var markerSentido = createMarkerSentido(point, iconSentido.clone());
			var marker = createMarker(point, iconMovil.clone(), carId);
			misVehiculosMarkersHash.put(carId, marker);
			misVehiculosSentidoHash.put(carId, markerSentido);
			vehiculosLayer.addMarker(markerSentido);
			vehiculosLayer.addMarker(marker);
			}
		else{
			vehiculosLayer.removeMarker(misVehiculosSentidoHash.get(carId));
			vehiculosLayer.removeMarker(misVehiculosMarkersHash.get(carId));
			misVehiculosSentidoHash.get(carId).icon = iconSentido.clone();
			misVehiculosSentidoHash.get(carId).lonlat = point;
			misVehiculosMarkersHash.get(carId).lonlat = point;
			vehiculosLayer.addMarker(misVehiculosSentidoHash.get(carId));
			vehiculosLayer.addMarker(misVehiculosMarkersHash.get(carId));
			}
	}
		
/*****************************************************************************/
//CENTRO DE COMANDOS
var procesadoComandoFlag = false;
var comandoResponse = null;

var reqHandlerSaveComando = null;
var reqHandlerRecibirComando = null;
var countCommandsDisplayed = 0; //cantidad de comandos enviados e impresos en el display.

var comandoTimeMIN = 0;
var comandoTimeSEG = 0;

var comandoRefreshTimeOutLIMIT = 30; //limite en segundos
var comandoRefreshClockIntervalLIMIT = 1; //limite en segundos

var comandoRefreshTimeOut;
var comandoRefreshTimeInterval;

var stopCommandProcess = false;

function cleanEstadoCentroDeComandos(){
	hideDiv('div_centroComandos');
	showDiv('div_vehiculosPpal');
}

function printTableComandos(){
	table = '<table>';
	table += '<tr>';
	table += '<td>';
	if (comandoResponse == null)
		table += ' <span class="inputLBL">Esperando respuesta del movil...</span>';
	else
		table += ' <span class="inputLBL">comandoResponse</span>';
	table += '</td>';
	table += '</tr>';
	table = '</table>';
	document.getElementById('divComandosList').innerHTML = table;
}

   function addOptionsToComandosVehiculoSelector(){
		var misVehiculosList = misVehiculosHash.values();
		if (misVehiculosList.length>0){
		   selector = document.getElementById('comandosMovil');
		   selector.options.length=0; //remove all options
		   for (var i=0; i<misVehiculosList.length; i++){
			 if (misVehiculosList[i]!='toJSONString'){
				 newOption = document.createElement('option');
				 newOption.value = misVehiculosList[i].id;
				 newOption.text = misVehiculosList[i].label;
				   try {
    					selector.add(newOption, null); // para todos los browsers (STANDART)
					   }
				  catch(ex) {
					    selector.add(newOption); // para IE
					   }				 
			 }
		   }
		}		
	}


function centroDeComandos(idVehiculo){	
	addOptionsToComandosVehiculoSelector();
	hideDiv('div_vehiculosPpal');
	showDiv('div_centroComandos');
	if (!procesadoComandoFlag){
		if (idVehiculo!=null){
			document.getElementById('comandosMovil').value=idVehiculo;
		}	
	}			
}

function validarSendCommand(){
	if (trim(document.getElementById('comandosInput').value).length==0){
		alert("El comando no es valido.");
		return false;
	}
	return true;
		
}

	function disabledSendCommand(disabled){
		disabledTXT="disabled";
		if (!disabled){
			disabledTXT="";
			document.getElementById('comandosInput').value="";
		}
		document.getElementById('comandosInput').disabled=disabledTXT;	
		document.getElementById('comandosMovil').disabled=disabledTXT;
		document.getElementById('comandosSendButton').disabled=disabledTXT;
		
	}
	
	function getTextFromCommandState(state){
		switch(state){
			case -1: return 'Enviando comando al servidor.';
			case 0: return 'Enviando comando al movil.';
			case 1: return 'Esperando respuesta del movil.';
			case 2: return 'OK - El movil respondio al comando.';
			default: return 'DESCONOCIDO.';
		}
	}
	
	function printComando(command, type){
		var line='';
		switch (parseInt(type)){
			//linea de envio de comando(texto)
			case 0: countCommandsDisplayed++;
					line='<div class="commandSendLine">'+command+'<div class="commandTimerDisplay" id=commandTimerDisplay'+countCommandsDisplayed+'>00:00</div></div>';
 					break;
		    //linea de recepcion de comando
			case 1: line='<div class="commandReceiveLine" id="commandReceive'+countCommandsDisplayed+'">'+command+'</div>';
					break;
			 //linea de recepcion de comando
			case 9: line='<div class="commandErrorLine">'+command+'</div>';
					break;
			default: line='<div><b>UNKNOW: </b>'+command+'</div>';
			}
		document.getElementById('divComandosList').innerHTML+=line;
		document.getElementById('divComandosList').scrollTop=document.getElementById('divComandosList').scrollHeight;
	}
		
	
	function OnReadyStateChangeRecibirComando(){
		if (!stopCommandProcess){
			ready = reqHandlerRecibirComando.readyState;
			if (ready == READY_STATE_COMPLETE) {
				var comandoResJSON = reqHandlerRecibirComando.responseText.parseJSON();
				if ((comandoResJSON != null)&&(comandoResJSON != 'undefined')&&(comandoResJSON != false)) {
					var lineReceive = '<b>Estado: </b>'+ getTextFromCommandState(parseInt(comandoResJSON.estado));
					var idResponse ='commandReceive'+countCommandsDisplayed;
					document.getElementById(idResponse).innerHTML = lineReceive;
					if (parseInt(comandoResJSON.estado)==2){ //termino el envio-recepcion de comandos!
						stopCommandProcess = true;
						clearInterval(comandoRefreshTimeInterval);
						clearTimeout(comandoRefreshTimeOut);
						comandoResponse = null;
						disabledSendCommand(false);
					}
				}
				document.getElementById("comandosBusyImg").style.visibility = "hidden";	
				recibirComando();
			}
		}
	}
	
	function recibirComando() {	
		if (!stopCommandProcess){
	    	reqParamsRecibirComando = "COMMAND=REFRESH";
			reqParamsRecibirComando += "&ID="+comandoResponse.id;
		    document.getElementById("comandosBusyImg").style.visibility = "visible";
    		if (msie) 
            	reqHandlerRecibirComando = new ActiveXObject("Microsoft.XMLHTTP");
		    else
    		    reqHandlerRecibirComando = new XMLHttpRequest();			
			reqHandlerRecibirComando.onreadystatechange = OnReadyStateChangeRecibirComando;    
		    reqHandlerRecibirComando.open("POST", "persistircomando.php", true);
    		reqHandlerRecibirComando.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			reqHandlerRecibirComando.send(reqParamsRecibirComando);
		}
    }
	
	function autoRefreshCommandClock(){
		if (comandoResponse!=null){
			comandoTimeSEG=comandoTimeSEG+comandoRefreshClockIntervalLIMIT;
			if (comandoTimeSEG > 60){
				comandoTimeSEG=0;
				comandoTimeMIN++;
			}
			var tiempoString = ((comandoTimeMIN < 10) ? '0' + comandoTimeMIN : comandoTimeMIN) 
								+'<blink>:</blink>'
								+((comandoTimeSEG < 10) ? '0' + comandoTimeSEG : comandoTimeSEG);
			document.getElementById('commandTimerDisplay'+countCommandsDisplayed).innerHTML = tiempoString;			
		}
	}
	
	function activateRefreshCommand(){
		comandoRefreshTimeInterval = setInterval("autoRefreshCommandClock();", comandoRefreshClockIntervalLIMIT * 1000);
    	autoRefreshCommandClock();
		recibirComando();
	}
	
	function timeOutRefreshCommand(){ //funcion que se llama cuando se vence el tiempo de espera de una respuesta...
		if (comandoResponse!=null){			
			printComando('Se vencio el tiempo de espera para procesar este comando.',9);
			clearInterval(comandoRefreshTimeInterval);
			comandoResponse = null;
			stopCommandProcess = true;
			document.getElementById("comandosBusyImg").style.visibility = "hidden";
			disabledSendCommand(false);
			}
	}
	
	function cleanDisplayDeComandos(){
		if (!document.getElementById('comandosInput').disabled){
			document.getElementById('divComandosList').innerHTML="";
			countCommandsDisplayed = 0;
		}
	}

	function OnReadyStateChangeSaveComando(){
		ready = reqHandlerSaveComando.readyState;
		if (ready == READY_STATE_COMPLETE) {
			nuevoComandoJSON = reqHandlerSaveComando.responseText.parseJSON();
			if (nuevoComandoJSON.id != -1) {
				comandoResponse = nuevoComandoJSON;
				comandoTimeMIN = 0;
				comandoTimeSEG = 0;
				var lineReceive = '<b>Estado: </b>'+ getTextFromCommandState(parseInt(nuevoComandoJSON.estado));
				var idResponse ='commandReceive'+countCommandsDisplayed;
				document.getElementById(idResponse).innerHTML = lineReceive;		
				clearTimeout(comandoRefreshTimeOut);
	  			comandoRefreshTimeOut = setTimeout ( "timeOutRefreshCommand();", comandoRefreshTimeOutLIMIT * 1000 );
				activateRefreshCommand();
			}
			else{
				if (nuevoComandoJSON.id == -1)
					printComando('Ocurrio un error en la DB al tratar de guardar el comando.',9);
				else
					printComando('Error de conexion a la DB.',9);
				disabledSendCommand(false);
			}
			document.getElementById("comandosBusyImg").style.visibility = "hidden";			
		}
	}
	
	function guardarComando() {
		if (validarSendCommand()){	
			disabledSendCommand(true);
			comandoResponse = null;
			stopCommandProcess = false;
	    	reqParamsSaveComando = "COMMAND=SAVE";
			var Movil = misVehiculosHash.get(document.getElementById('comandosMovil').value.toString());
			comando = "PROPIO,"+document.getElementById('comandosInput').value;
			terminal = "WEB_"+"userlogueado";
			reqParamsSaveComando += "&ID=";
    		reqParamsSaveComando += "&CUENTA="+Movil.id;
			reqParamsSaveComando += "&MOVILID="+Movil.movil;
			reqParamsSaveComando += "&COMANDO="+comando;
			reqParamsSaveComando += "&ESTADO=0";
			reqParamsSaveComando += "&RECEPTORA=0";
    		reqParamsSaveComando += "&TERMINAL="+terminal;
	    	document.getElementById("comandosBusyImg").style.visibility = "visible";
    		if (msie) 
        	    reqHandlerSaveComando = new ActiveXObject("Microsoft.XMLHTTP");
	        else
    	        reqHandlerSaveComando = new XMLHttpRequest();			
			reqHandlerSaveComando.onreadystatechange = OnReadyStateChangeSaveComando;    
	        reqHandlerSaveComando.open("POST", "persistircomando.php", true);
    	    reqHandlerSaveComando.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			var lineSend = '<b>'+document.getElementById('comandosMovil').options[document.getElementById('comandosMovil').selectedIndex].text+'</b>';
			lineSend += ' >> ' + comando;
			printComando(lineSend,0);
			var lineReceive = '<b>Estado: </b>'+ getTextFromCommandState(-1);
			printComando(lineReceive,1);
			reqHandlerSaveComando.send(reqParamsSaveComando);
		}
    }


	